package com.bzxhh.lock;

import java.util.concurrent.locks.ReentrantLock;

//1.创建资源类 定义属性和操作方法
class LTicket {
    //票数
    private int number = 30;

    //可重入锁
    private final ReentrantLock lock = new ReentrantLock(true); //公平锁
//    private final ReentrantLock lock = new ReentrantLock(false); //非公平锁

    //操作方法；卖票
    public void sale() {
        //上锁
        lock.lock();
        try {
            //判断是否可以卖票 数量-1
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + " :卖出: 1" + " 剩下: " + --number);
            }
        } finally {
            //解锁
            lock.unlock();
        }


    }
}

public class LSaleTicket {
    //创建多个线程，调用资源类得操作方法
    public static void main(String[] args) {
        LTicket lTicket = new LTicket();

        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                lTicket.sale();
            }
        },"t1").start();

        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                lTicket.sale();
            }
        },"t2").start();

        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                lTicket.sale();
            }
        },"t3").start();

    }
}
